<?php


namespace app\admin\model\Goods;


use app\admin\model\Merchant\MerchantModel;
use think\facade\Db;
use think\Model;

class GoodsModel extends Model
{
    /**
     * 数据表名
     * @var string
     */
    protected $name = "goods";

    /**
     * 根据条件查询单条数据
     * @param $where
     * @param string $field
     * @return mixed
     * @throws
     */
    public static function getGoodsWhere($where, $field = "*")
    {
        $goods = Db::name("goods")->field($field)->where($where)->find();
        return $goods;
    }

    /**
     * 商户
     */
    public function merchant()
    {
        return $this->hasOne(MerchantModel::class, 'id', 'mer_id');
    }

    /**
     * 根据条件查询多条数据
     * @param $where
     * @return mixed
     * @throws
     */
    public static function getGoodsWhereMore($where)
    {
        $list = Db::name("goods")->where($where)->select()->toArray();
        return $list;
    }

    /**
     * 统计总数
     * @param $where
     * @return int
     */
    public static function getGoodsCountWhere($where)
    {
        $count = Db::name("goods")->where($where)->count();
        return $count;
    }

    /**
     * 分页查询
     * @param $page
     * @param $limit
     * @param $where
     * @return mixed
     * @throws
     */
    public static function getGoodsListWhere(string $good_name, int $is_group, int $is_show, $account, $page, $limit)
    {
        $start = ceil(($page - 1) * $limit);
        $list = GoodsModel::with(['merchant' => function ($query) {
            return $query->field('id,account');
        }])

            ->when($good_name, function ($query) use ($good_name) {
                return $query->where('good_name', 'like', '%' . $good_name . '%');
            })
            ->hasWhere('merchant', function ($query) use ($account) {
                return $query->where('account', 'like', '%' . $account . '%');
            })
            ->where('GoodsModel.is_group', $is_group)
            ->where('GoodsModel.is_show', $is_show)
            ->limit($start, $limit)
            ->select();
        $data = $list->toArray();
        $count = $list->count();
        return compact('data', 'count');
    }

    /**
     * 添加返回ID
     * @param $data
     * @return int
     */
    public static function addGoods($data)
    {
        $id = Db::name('goods')->insertGetId($data);
        return $id;
    }

    /**
     * 更新
     * @param $where
     * @param $save
     * @return int
     * @throws
     */
    public static function updateGoodsWhere($where, $save)
    {
        $flag = Db::name('goods')->where($where)->update($save);
        return $flag;
    }

    /**
     * 删除
     * @param $where
     * @return int
     * @throws
     */
    public static function delGoodsWhere($where)
    {
        $flag = Db::name('goods')->where($where)->delete();
        return $flag;
    }
}
